<script setup>
import { useEventListener } from '@vueuse/core'
import useChannel from '@/store/channel'
import useUser from '@/store/user'
import { scrollIntoView } from '@/utils'
import SvgIcon from '@/components/SvgIcon.vue'

const props = defineProps({
  word: {
    type: String,
    default: '',
  },
})
const emit = defineEmits(['select', 'close'])
const channelStore = useChannel()
const userStore = useUser()
// -1 默认是全体人员
const activeIndex = ref(-1)
const userRef = ref([])
const allUserRef = ref(null)
const filterUser = computed(() => {
  return channelStore.members.filter(
    (i) => i.realName && i.userId !== userStore.userInfo.userId && i.realName.includes(props.word)
  )
})

watch(
  () => filterUser.value.length,
  (length) => {
    if (length < channelStore.members.length) {
      activeIndex.value = 0
    } else {
      activeIndex.value = -1
    }
  }
)

watch(activeIndex, (newVal) => {
  if (newVal === -1) scrollIntoView(allUserRef, false)
  else scrollIntoView(userRef.value[newVal], false)
})

/**
 * 手动点击选择用户
 */
function selectUser(user, index) {
  emit('select', {
    text: user.realName,
    list:
      index === -1 ? channelStore.members.filter((i) => i.realName && i.userId !== userStore.userInfo.userId) : [user],
  })
}

useEventListener('keydown', (e) => {
  // 退出
  if (e.code === 'Escape') {
    emit('close')
    // 向上选择
  } else if (e.code === 'ArrowUp') {
    if (activeIndex.value === -1) {
      activeIndex.value = filterUser.value.length - 1
    } else {
      activeIndex.value--
    }
    // 向下选择
  } else if (e.code === 'ArrowDown') {
    if (activeIndex.value === filterUser.value.length - 1) {
      activeIndex.value = -1
    } else {
      activeIndex.value++
    }
    // 确认选择
  } else if (e.code === 'Enter' || e.code === 'NumpadEnter') {
    selectUser(filterUser.value[activeIndex.value] || { realName: '全体人员' }, activeIndex.value)
  }
})
</script>

<template>
  <div class="mention-user">
    <div
      ref="allUserRef"
      class="user-item"
      :class="{ active: activeIndex === -1 }"
      @click="selectUser({ realName: '全体人员' }, -1)">
      <SvgIcon name="logo" circle size="30px"></SvgIcon>
      <span>全体人员</span>
    </div>
    <div
      ref="userRef"
      class="user-item"
      :class="{ active: activeIndex === index }"
      v-for="(item, index) in filterUser"
      :key="item.id"
      @click="selectUser(item, index)">
      <SvgIcon :src="channelStore.userAvatarMap.get(item.userId)" circle size="30px"></SvgIcon>
      <span>{{ item.realName }}</span>
    </div>
  </div>
</template>

<style scoped lang="scss">
.mention-user {
  height: 100%;
  width: 300px;
  overflow-y: auto;
  .user-item {
    @include use-flex(center);
    cursor: pointer;
    font-size: 16px;
    padding: 5px 10px;
    span {
      padding-left: 10px;
    }
    &.active,
    &:hover {
      border-radius: 4px;
      background-color: var(--elp-color-info-light-9);
    }
  }
}
</style>
